/*
 * @Description: 
 * @Author: fhw
 * @Date: 2022-12-19 13:53:35
 */
import { Body, Controller, Get, HttpCode, Post, Query, UseFilters } from '@nestjs/common';
import { ApiBody, ApiOperation, ApiQuery, ApiResponse, ApiTags } from '@nestjs/swagger';
import { isNil, isEmpty, clone } from 'ramda';
import { ChatUserService } from 'src/chat_user/chat_user.service';
import { ChatUser } from 'src/chat_user/entities/chat_user.entity';
import { HttpExceptionFilter } from 'src/http-exception.filter';
import { throwHttp } from 'src/utlis';
import { CreateleaveAMessageDto, GetUserPageDto } from './dto/message-board.dto';
import { MessageBoardService } from './message-board.service';
@ApiTags('留言板')
@Controller('message-board')
export class MessageBoardController {
  constructor(private readonly messageBoardService: MessageBoardService, private readonly chatUserService: ChatUserService,) { }

  @Get('/getMessageBoardPage')
  @ApiResponse({
    status: 200,
    description: '留言板分页',
    type: GetUserPageDto,
  })
  @ApiOperation({ summary: '留言板分页', operationId: 'getMessageBoardPage'  })
  @UseFilters(new HttpExceptionFilter())
  async getMessageBoardPage(@Query() params: GetUserPageDto) {
    try {
      const data = await this.messageBoardService.getMessageBoardPage(params);
      const messageBoardList = []
      for (const iterator of data.data) {
        const item = clone(iterator)
        const user = clone(item.user)
        delete item.user
        const twoMessageBoard = []
        // 二级评论增加用户名称
        for (const res of item.twoMessageBoard) {
          const userInfo = await this.chatUserService.getUserInfo({ id: res.userId })
          const toUserInfo = await this.chatUserService.getUserInfo({ id: res.toUserId })
          twoMessageBoard.push({
            ...res,
            toUserName: toUserInfo.username,
            username: userInfo.username,
          })
        }
        messageBoardList.push({
          ...item,
          twoMessageBoard,
          username: user.username
        })
      }
      data.data = messageBoardList
      return data
    } catch (error) {
      throwHttp(error.message)
    }
  }

  @HttpCode(200)
  @Post('/createleaveAMessage')
  @ApiQuery({
    description: '创建留言',
    type: CreateleaveAMessageDto,
  })
  @ApiBody({ description: '创建留言', type: CreateleaveAMessageDto })
  @ApiOperation({ summary: '创建留言' , operationId: 'createleaveAMessage' })
  @UseFilters(new HttpExceptionFilter())
  async createleaveAMessage(@Body() body: CreateleaveAMessageDto) {
    const { userId, toUserId, messageBoardId } = body
    const user = await this.chatUserService.getUserInfo({ id: userId })
    let toUser: ChatUser
    if (!isNil(messageBoardId) && !isEmpty(messageBoardId)) {
      const users = await this.chatUserService.getUserInfo({ id: toUserId })
      toUser = users
    }
    return await this.messageBoardService.createleaveAMessage(body, { user, toUser })
  }

}
